import mysql from "mysql";
import { Component } from "./domain/Component";
export class Database {
  tableName: string = "components";
  databaseName: string = "lowCode"
  connection = mysql.createConnection({
    host: "localhost",
    user: "laremehpe",
    password: "1098628245",
    database: "lowCode",
  });

  constructor() {
    this.connection.connect((err) => {
      if (err) throw err;
      console.log("Connected!");
    });

    this.init()
  }

  private init() {
    this.connection.query(`
      CREATE TABLE IF NOT EXISTS ${this.tableName} (
        id INT AUTO_INCREMENT,
        name VARCHAR(255),
        label VARCHAR(255),
        path VARCHAR(255),
        thumbnail TEXT,
        description TEXT,
        create_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
        PRIMARY KEY (id)
    );
      `)
  }

  public queryComponent(pageSize: number = 10, pageNo: number = 1) {
    return new Promise((resolve, reject) => {
      this.connection.query(
        `SELECT * FROM ${this.tableName} LIMIT ${pageSize} OFFSET ${(pageNo - 1) * pageSize
        }`,
        (err, result) => {
          if (err) reject(err);
          resolve(result);
        }
      );
    });
  }
  public addComponent(data: Component) {
    return new Promise((resolve, reject) => {
      const sql =
        `INSERT INTO ${this.tableName} (name, path, label, thumbnail, description) values ("${data.name}", "${data.path}", "${data.label}", "${data.thumbnail}", "${data.description}")`
      console.log(sql);

      this.connection.query(
        sql,
        data,
        (err, result) => {
          if (err) reject(err);
          resolve(result);
        }
      );
    });
  }

  public delComponent(id: string | number) {
    return new Promise((resolve, reject) => {
      const sql =
        `delete from ${this.tableName} where id="${id}"`
      console.log(sql);

      this.connection.query(
        sql,
        "",
        (err, result) => {
          if (err) reject(err);
          resolve(result);
        }
      );
    })
  }
}
